#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
##############################################################################
# Descrição:
# Esse módulo define uma engine de tiles muito simples. Ele é usado no
# editor de mapas. Se for rodado como um script ele executa alguns testes
#
# Autor: Kao Cardoso Félix
#
# Dependências:
#   - python >= 2.5
#   - pygame (http://www.pygame.org)
##############################################################################

import sys
import math

import pygame
from pygame.locals import *

TILE_BASE_SIZE = 16

class TileSet(object):
    def __init__(self, tileset_file, scale=1):
        tiles = pygame.image.load(tileset_file)
        
        self.w = (tiles.get_width() / TILE_BASE_SIZE)
        self.h = (tiles.get_height() / TILE_BASE_SIZE)
        
        self.tile_size = TILE_BASE_SIZE*scale
        self.tiles = pygame.transform.scale(tiles, (self.w*self.tile_size, self.h*self.tile_size)) #.convert()

        self.size = self.w * self.h
        
        
        self._gen_water_tiles()
    
    def __iter__(self):
        index = 0
        while True:
            tile = self[index]
            if tile:
                yield tile
            else:
                raise StopIteration
            index += 1
            
    
    def __getitem__(self, index):
        (y, x) = divmod(index, self.w)
        if x+1 > self.w or y+1 > self.h:
            return None
        return self.tiles.subsurface((x*self.tile_size, y*self.tile_size, self.tile_size, self.tile_size))
    
    def __len__(self):
        return self.size
        
    def _gen_water_tiles(self):
        pass
        #~ water_x = 3
        #~ self.water_tile = pygame.Surface((5*TileSet.TILE_DIM, 3*TileSet.TILE_DIM))
        
        #~ water_closed = self._get_tile(water_x, 0)
        #~ water_closed_v = self._get_tile(water_x, 1)
        #~ water_closed_h = self._get_tile(water_x, 2)
        #~ water_corners = self._get_tile(water_x, 3)
        #~ water_open = self._get_tile(water_x, 4)
        
        #~ for x in range(3):
            #~ for y in range(3):
                #~ self.water_tile.blit(water_open, (x*TileSet.TILE_DIM, y*TileSet.TILE_DIM))
                

class TileLayer(object):
    def __init__(self, tileset, map):
        self.tileset = tileset
        self.map = map
    
    def draw_region(self, surface, rect):
        x1, y1 = rect.topleft
        x2, y2 = rect.bottomright
        
        x1 = math.floor(float(x1)/self.tileset.tile_size)
        y1 = math.floor(float(y1)/self.tileset.tile_size)
        
        x2 = math.ceil(float(x2)/self.tileset.tile_size)
        y2 = math.ceil(float(y2)/self.tileset.tile_size)

        print x1,y1,x2,y2

test_map_w, test_map_h = 100, 100
test_map = [[0]*test_map_w for i in range(test_map_h)]

layers = 3

if __name__ == '__main__':
    render_pos = (32, 32)
    
    pygame.init()
    pygame.display.set_mode((640,480))
    
    tileset = TileSet('tiles.png', 2)
    layer = TileLayer(tileset, map)
    
    layer.draw_region(None, Rect(16, 16, 320, 240))
    
    print tileset.w, tileset.h
    
    display_rect = pygame.display.get_surface().get_rect()
    
    FPS = None
    
    while True:
        time_start = pygame.time.get_ticks()
        
        #~ for i, tile in enumerate(tileset):
            #~ pygame.display.get_surface().blit(tile, (render_pos[0]+i*TileSet.TILE_DIM, render_pos[1]))
        
        #pygame.display.get_surface().blit(tileset.water_tile, (render_pos[0], render_pos[1]))
        
        for n in range(layers):
            for x in range(display_rect.w/tileset.tile_size):
                for y in range(display_rect.h/tileset.tile_size):
                    pygame.display.get_surface().blit(tileset[0], (x * tileset.tile_size, y * tileset.tile_size))
        
        pygame.display.flip()
        
        time_delta = pygame.time.get_ticks() - time_start
        if FPS:
            FPS += 1000.0 / time_delta
            FPS /= 2
        else:
            FPS = 1000.0 / time_delta
        
        ev = pygame.event.poll()
        if ev and ev.type == KEYDOWN:
            if ev.key == K_ESCAPE:
                print FPS
                sys.exit(0)
        elif ev.type == QUIT:
            print FPS
            sys.exit(0)